import React, { useEffect, useState } from 'react';
import classNames from 'classnames';
import dayjs from 'dayjs';
import _ from 'lodash';

import { http } from './utils/http';

// 分拆的组件
import CommentCount from './components-hooks/CommentCount';
import Tabs from './components-hooks/Tabs';
import Forms from './components-hooks/Forms';
import CommentList from './components-hooks/CommentList';

import './Comments.css'; // 导入样式

const LIST_KEY = 'list';

export const Comments = () => {
  // 列表
  // const [list, setList] = useState(
  //   JSON.parse(localStorage.getItem('B-list') || '[]')
  // );
  const [list, setList] = useState([]);
  // tabs
  const [tabs, setTabs] = useState([
    {
      id: 1,
      name: '热度',
      type: 'hot',
    },
    {
      id: 2,
      name: '时间',
      type: 'time',
    },
  ]);
  // 选中
  const [active, setActive] = useState('hot');

  // tab切换
  const changeTab = (type) => {
    console.log(type);
    if (type === 'hot') {
      // id 降序
      const newList = list.sort((a, b) => {
        // a-b 升序，b-a 降序
        return b.id - a.id;
      });
      // 刷新页面
      setList(newList);
      setActive(type);
    } else {
      // 时间升序
      // 使用第三方库实现排序
      const newList = _.orderBy(list, ['time'], ['asc']);
      setList(newList);
      setActive(type);
    }
  };

  // 删除
  const delComment = (id) => {
    console.log(id);
    const newList = list.filter((item) => item.id !== id);

    // 刷新页面
    setList(newList);
  };
  // 点赞和踩
  const changeAttitude = (id, newAttitude) => {
    console.log(id, newAttitude);
    const newList = list.map((item) => {
      if (item.id === id) {
        return { ...item, attitude: newAttitude };
      } else {
        return item;
      }
    });
    // 刷新页面
    setList(newList);
  };
  // 发表评论
  const addComment = (txt) => {
    console.log(txt);
    const comment = {
      id: Date.now(),
      author: '刘德华',
      comment: txt,
      time: new Date(),
      // 1: 点赞 0：无态度 -1:踩
      attitude: 1,
    };
    setList([comment, ...list]);
  };

  // componentDidMount() {
  //   console.log('componentDidMount');
  //   // 发起网络请求
  //   // 从本地读取评论数据
  //   const list = JSON.parse(localStorage.getItem(LIST_KEY) || '[]');
  //   this.setState({ list: list });
  // }

  // 持久化存储评论数据
  // componentDidUpdate() {
  //   console.log('componentDidUpdate');
  //   localStorage.setItem(LIST_KEY, JSON.stringify(this.state.list));
  // }

  // 当组件的 list 发生变化的时候，useEffect 执行
  // useEffect(() => {
  //   // 保存数据本地
  //   localStorage.setItem('B-list', JSON.stringify(list));
  // }, [list]);
  useEffect(() => {
    console.log('准备请求数据');
    const fetchData = async () => {
      const listRes = await http.get('/list');
      console.log(listRes);
      setList(listRes.data);
    };
    fetchData();
  }, []);

  return (
    <div className="comment-root">
      <div className="comment-container">
        <CommentCount count={list.length} />
        <Tabs tabs={tabs} active={active} changeTab={changeTab} />
        <Forms addComment={addComment} />
        <CommentList
          list={list}
          delComment={delComment}
          changeAttitude={changeAttitude}
        />
      </div>
    </div>
  );
};

export class Comments1 extends React.Component {
  constructor() {
    super();

    // 推荐在 componentDidMount 中初始化，获取数据。
    // const list = JSON.parse(localStorage.getItem(LIST_KEY) || '[]');
    this.state = {
      // hot: 热度排序  time: 时间排序
      tabs: [
        {
          id: 1,
          name: '热度',
          type: 'hot',
        },
        {
          id: 2,
          name: '时间',
          type: 'time',
        },
      ],
      active: 'hot',
      list: [],
      // 用户输入的评论
      txt: '',
    };
  }

  // tab切换
  changeTab = (type) => {
    console.log(type);
    if (type === 'hot') {
      // id 降序
      const newList = this.state.list.sort((a, b) => {
        // a-b 升序，b-a 降序
        return b.id - a.id;
      });
      // 刷新页面
      this.setState({
        active: type,
        list: newList,
      });
    } else {
      // 时间升序
      // 使用第三方库实现排序
      const newList = _.orderBy(this.state.list, ['time'], ['asc']);
      this.setState({
        active: type,
        list: newList,
      });
    }
  };

  // 删除
  delComment = (id) => {
    console.log(id);
    const newList = this.state.list.filter((item) => item.id !== id);

    // 刷新页面
    this.setState({
      list: newList,
    });
  };
  // 点赞和踩
  changeAttitude = (id, newAttitude) => {
    console.log(id, newAttitude);
    const newList = this.state.list.map((item) => {
      if (item.id === id) {
        return { ...item, attitude: newAttitude };
      } else {
        return item;
      }
    });
    // 刷新页面
    this.setState({
      list: newList,
    });
  };
  // 发表评论
  addComment = (txt) => {
    console.log(txt);
    const comment = {
      id: Date.now(),
      author: '刘德华',
      comment: txt,
      time: new Date(),
      // 1: 点赞 0：无态度 -1:踩
      attitude: 1,
    };
    this.setState({
      list: [comment, ...this.state.list],
    });
  };

  componentDidMount() {
    console.log('componentDidMount');
    // 发起网络请求
    // 从本地读取评论数据
    const list = JSON.parse(localStorage.getItem(LIST_KEY) || '[]');
    this.setState({ list: list });
  }

  // 持久化存储评论数据
  componentDidUpdate() {
    console.log('componentDidUpdate');
    localStorage.setItem(LIST_KEY, JSON.stringify(this.state.list));
  }

  render() {
    return (
      <div className="comment-root">
        <div className="comment-container">
          <CommentCount count={this.state.list.length} />
          <Tabs
            tabs={this.state.tabs}
            active={this.state.active}
            changeTab={this.changeTab}
          />
          <Forms addComment={this.addComment} />
          <CommentList
            list={this.state.list}
            delComment={this.delComment}
            changeAttitude={this.changeAttitude}
          />
        </div>
      </div>
    );
  }
}
